package com.mszlu.blog.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.mszlu.blog.dao.mapper.AdminMapper;
import com.mszlu.blog.dao.mapper.BannedMapper;
import com.mszlu.blog.dao.pojo.Admin;
import com.mszlu.blog.dao.pojo.Banned;
import com.mszlu.blog.dao.pojo.SysUser;
import com.mszlu.blog.service.LoginService;
import com.mszlu.blog.service.SysUserService;
import com.mszlu.blog.utils.EmptyUtils;
import com.mszlu.blog.utils.JWTUtils;
import com.mszlu.blog.vo.ErrorCode;
import com.mszlu.blog.vo.Result;
import com.mszlu.blog.vo.params.LoginParam;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Package: com.mszlu.blog.service.impl
 * @ClassName: LoginServiceImpl
 * @Author: 陈威
 * @CreateTime: 2021/8/30 16:32
 * @Description:
 */
@Service
@Transactional
public class LoginServiceImpl implements LoginService {
    //加盐
    private static final String slat = "mszlu!@#";
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    BannedMapper bannedMapper;

    //登录验证 返回token
    @Override
    public Result login(LoginParam loginParam) {
        /**
         * 1. 检查参数是否合法
         * 2. 根据用户名和密码去user表中查询 是否存在
         * 3. 如果不存在 登录失败
         * 4. 如果存在 ，使用jwt 生成token 返回给前端
         * 5. token放入redis当中，redis  token：user信息 设置过期时间
         *  (登录认证的时候 先认证token字符串是否合法，去redis认证是否存在)
         */
        String account = loginParam.getAccount();
        String password = loginParam.getPassword();
        String isAdmin = loginParam.getIsAdmin();
        if (StringUtils.isBlank(account) || StringUtils.isBlank(password)) {
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
        }
        password = DigestUtils.md5Hex(password + slat);
        //管理员登录
        if ("1".equals(isAdmin)) {
            Admin adminUser = adminMapper.findAdminUser(account, password);
            if (adminUser == null) {
                return Result.fail(ErrorCode.ACCOUNT_PWD_NOT_EXIST.getCode(), ErrorCode.ACCOUNT_PWD_NOT_EXIST.getMsg());
            }
            String token = JWTUtils.createToken(adminUser.getId());

            redisTemplate.opsForValue().set("TOKEN_Admin_" + token, JSON.toJSONString(adminUser), 1, TimeUnit.HOURS);
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            map.put("username", adminUser.getAccount());
            return Result.success(map);
        } else {
            SysUser sysUser = sysUserService.findUser(account, password);

            if (sysUser == null) {
                return Result.fail(ErrorCode.ACCOUNT_PWD_NOT_EXIST.getCode(), ErrorCode.ACCOUNT_PWD_NOT_EXIST.getMsg());
            }

            //先验证该用户是否已被封号
            Banned banned = checkIsBanned(sysUser.getId());
            if (banned!=null){
                String time = DateUtil.formatDateTime(new Date(banned.getBannedCode()));
                return Result.fail(999,"该账号已被封禁,该账号将封禁至："+time);
            }

            String token = JWTUtils.createToken(sysUser.getId());
            redisTemplate.opsForValue().set("TOKEN_" + token, JSON.toJSONString(sysUser), 1, TimeUnit.HOURS);
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            map.put("username", sysUser.getNickname());
            return Result.success(map);
        }
    }

    @Override
    public SysUser checkToken(String token) {
        /*
         1.token合法性校验
            是否为空,解析是否成功 redus是否存在
            2.如果校验失败返回错误
            3.如果检验成功，返回对应的结果

         **/
        if (StringUtils.isBlank(token)) {
            return null;
        }
        Map<String, Object> stringObjectMap = JWTUtils.checkToken(token);
        if (stringObjectMap == null) {
            return null;
        }
        String userJson = redisTemplate.opsForValue().get("TOKEN_" + token);
        if (StringUtils.isBlank(userJson)) {
            return null;
        }
        SysUser sysUser = JSON.parseObject(userJson, SysUser.class);
        return sysUser;
    }

    public Banned checkIsBanned(Long uid) {
        Banned banned = bannedMapper.selectByUid(uid);
        return banned;
    }

    @Override
    public Admin checkAdminToken(String token) {
        /*
         1.token合法性校验
            是否为空,解析是否成功 redus是否存在
            2.如果校验失败返回错误
            3.如果检验成功，返回对应的结果

         **/
        if (StringUtils.isBlank(token)) {
            return null;
        }
        Map<String, Object> stringObjectMap = JWTUtils.checkToken(token);
        if (stringObjectMap == null) {
            return null;
        }
        String userJson = redisTemplate.opsForValue().get("TOKEN_Admin_" + token);
        if (StringUtils.isBlank(userJson)) {
            return null;
        }
        Admin admin = JSON.parseObject(userJson, Admin.class);
        return admin;
    }

    //退出登录
    @Override
    public Result logout(String token) {
        redisTemplate.delete("TOKEN_" + token);
        return Result.success(null);
    }

    //注册
    @Override
    public Result register(LoginParam loginParam) {
        /**
         * 1. 判断参数 是否合法
         * 2. 判断账户是否存在，存在 返回账户已经被注册
         * 3. 不存在，注册用户
         * 4. 生成token
         * 5. 存入redis 并返回
         * 6. 注意 加上事务，一旦中间的任何过程出现问题，注册的用户 需要回滚
         */
        String account = loginParam.getAccount();
        String password = loginParam.getPassword();
        String nickname = loginParam.getNickname();
        if (StringUtils.isBlank(account)
                || StringUtils.isBlank(password)
                || StringUtils.isBlank(nickname)
        ) {
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
        }
        SysUser sysUser = sysUserService.findUserByAccount(account);
        if (sysUser != null) {
            return Result.fail(ErrorCode.ACCOUNT_EXIST.getCode(), "账户已经被注册了");
        }
        sysUser = new SysUser();
        sysUser.setNickname(nickname);
        sysUser.setAccount(account);
        sysUser.setPassword(DigestUtils.md5Hex(password + slat));
        sysUser.setCreateDate(System.currentTimeMillis());
        sysUser.setLastLogin(System.currentTimeMillis());
        sysUser.setAvatar("/static/img/logo.b3a48c0.png");
        sysUser.setAdmin(1); //1 为true
        sysUser.setDeleted(0); // 0 为false
        sysUser.setSalt("");
        sysUser.setStatus("");
        sysUser.setEmail("");
        sysUserService.save(sysUser);
        SysUser returnUser = sysUserService.findUserByAccount(account);
        String token = JWTUtils.createToken(sysUser.getId());

        redisTemplate.opsForValue().set("TOKEN_" + token, JSON.toJSONString(sysUser), 1, TimeUnit.DAYS);
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("username", returnUser.getNickname());
        return Result.success(map);
    }

}
